package com.bdsy.business.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.bdsy.business.dao.UserInfoMapper;
import com.bdsy.business.model.UserInfo;
import com.bdsy.common.utils.DateRandomUtil;

@Service("userInfoService")
public class UserInfoServiceImpl implements com.bdsy.business.service.UserInfoService {

	@Autowired
	UserInfoMapper userInfoMapper;
	
	@Override
	public List<UserInfo> selectUserInfoById(String userId) {
		List<UserInfo> userInfo = userInfoMapper.selectUserInfoById(userId);
		return userInfo;
	}

	@Override
	public boolean updateUserInfo(UserInfo userInfo,MultipartFile file) {
		//图片上传
		//服务器项目目录路径
//		String path = "E:\\Program Files\\Apache Software Foundation\\apache-tomcat-8.5.23\\webapps\\adicms_image\\head";
//		String path = "D:\\Program Files\\Apache Software Foundation\\apache-tomcat-8.5.23\\webapps\\adicms_image\\head";
	    String path = "/usr/local/tomcat/webapps/adicms_image/head";
		if(file !=null){
			//文件类型
			String contentType = file.getContentType();
			//获得文件后缀名   
	        String suffixName=contentType.substring(contentType.indexOf("/")+1); 
	        //生成uuid作为文件名称    
//	        String uuid = UUID.randomUUID().toString().replaceAll("-","");    
	        //生成当前日期加五位随机数作为文件名称    
            String cfileName = DateRandomUtil.getRandomFileName();  
	        //得到 文件名  
	        String fileName=cfileName+"."+suffixName;  
	        
	        System.out.println(path+"--***---"+contentType+"--***---"+suffixName+"---***---"+fileName);
			//生成文件
		    File dir = new File(path, fileName);  
	        if(!dir.exists()){  
	            dir.mkdirs();  
	        }   
	        System.out.println(dir.getAbsolutePath()+"///////");
	        try {
				file.transferTo(dir);
			}catch (IOException e) {
				System.out.println("文件转换失败");
				e.printStackTrace();
			}
	        //把图片的相对路径保存至数据库
	       String url= "/head/" + fileName;
	       userInfo.setPortrait(url);
		}
	       int result = userInfoMapper.updateUserInfo(userInfo);
	       return result>0?true:false;
	}

	@Override
	public boolean addUserInfo(UserInfo userInfo) {
		int number = (int)((Math.random()*9+1)*10000000);
		userInfo.setId(number);
		int result = userInfoMapper.insert(userInfo);
	    return result>0?true:false;
	}

}
